import React, { useImperativeHandle, useRef, useState } from 'react';
import { Form, Modal } from 'antd';

import { getSeatSoundTempList } from 'seats/servers/servers';
import { FetchDataParam, FetchDataResponse, PageSelect } from 'components/UILibrary/pageSelect';
import { clearNull, verifyNull } from 'utils/tools';
import { TaskInfo } from 'seats/schema/Task';
import { useDispatch } from 'react-redux';

import { setSoundTemplateId } from '../../../../store/root/action';

// 弹窗ref
type IProps = {
  cRef: any;
};
// 存储回调函数
let ok = (soundTemplateId: number) => {};
const ChooseSoundPop: React.FC<IProps> = ({ cRef }) => {
  const [form] = Form.useForm();
  const dataRef = useRef<TaskInfo>();
  const dispatch = useDispatch(); // react-redux 触发action

  const [visible, setVisible] = useState<boolean>(false);

  const open = (obj: TaskInfo, cb: any) => {
    setVisible(true);
    ok = cb;
    // 弹窗
    console.log(obj, '添加录音弹窗');
    dataRef.current = obj;
  };

  useImperativeHandle(cRef, () => ({
    open: (obj: any, cb: any) => open(obj, cb),
  }));
  const handleOK = () => {
    form.validateFields().then(() => {
      // 表单验证通过
      const val = form.getFieldsValue();
      // 缓存-录音模板
      dispatch(setSoundTemplateId(val.soundRecordTemplateId));
      // 关闭弹窗
      handleClose();
      // 执行回调
      ok(val.soundRecordTemplateId);
    });
  };
  const handleClose = () => {
    // 恢复默认
    form.resetFields();
    setVisible(false);
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 },
  };
  /**
   * 查找录音模板列表的dataProvider--根据机器人ID查询，默认最新版本
   */
  const fetchSoundListByType = (args: FetchDataParam): FetchDataResponse => {
    return new Promise((resolve, reject) => {
      const obj: any = {
        pageNo: args.pageNum,
        pageSize: args.pageSize,
        robotId: dataRef.current?.robotId,
        templateStatus: 1, // 查询录音模板状态：已完成
        type: 1,
      };
      console.log(obj, '请求模板列表入参999');
      getSeatSoundTempList(clearNull(obj))
        .then(res => {
          resolve({
            data: (res.data as any).map((item: any) => {
              return {
                label: item.templateName,
                value: item.templateId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };
  return (
    <Modal width={520} title="请选择录音" visible={visible} onOk={handleOK} onCancel={handleClose}>
      <Form {...layout} form={form} layout="horizontal">
        <Form.Item
          label="录音模板"
          name="soundRecordTemplateId"
          rules={verifyNull('请选择录音模板')}
        >
          <PageSelect allowClear fetchData={fetchSoundListByType} placeholder="请选择录音模板" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ChooseSoundPop;
